<template>
  <div class="pb-3 validate-input-container">
    <input class="form-control" v-bind="$attrs" v-if="tag !== 'textarea'" :value="inputRef.val" @blur="validateInput"
      :class="{'is-invalid': inputRef.error}" @input="updateValue" :placeholder="placeholder" />
    <textarea class="form-control" v-bind="$attrs" v-else :value="inputRef.val" @blur="validateInput"
      :class="{'is-invalid': inputRef.error}" @input="updateValue" :placeholder="placeholder" />
    <span v-if="inputRef.error" class="invalid-feedback">{{ inputRef.message }}</span>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, PropType, onMounted } from 'vue'
import { emitter } from './ValidateForm.vue'
const emailReg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
interface RuleProp {
  type: 'required' | 'email' | 'username_min' | 'username_max' | 'password_min' | 'password_max',
  message: string
}
export type RulesProp = RuleProp[]
export type TagType = 'input' | 'textarea'
export default defineComponent({
  name: 'ValidateInput',
  props: {
    rules: Array as PropType<RulesProp>,
    modelValue: String,
    placeholder: String,
    tag: {
      type: String as PropType<TagType>,
      default: 'input'
    }
  },
  inheritAttrs: false,
  setup(props, context) {
    const inputRef = reactive({
      val: props.modelValue || '',
      error: false,
      message: ''
    })
    const updateValue = (e: KeyboardEvent) => {
      const targetValue = (e.target as HTMLInputElement).value
      inputRef.val = targetValue
      context.emit('update:modelValue', targetValue)
    }
    const validateInput = () => {
      if (props.rules) {
        const allPassed = props.rules.every(rule => {
          let passed = true
          inputRef.message = rule.message
          switch (rule.type) {
            case 'required':
              passed = !(inputRef.val.trim() === '')
              break
            case 'email':
              passed = emailReg.test(inputRef.val)
              break
            case 'username_min':
              passed = inputRef.val.length >= 3
              break
            case 'username_max':
              passed = inputRef.val.length <= 10
              break
            case 'password_min':
              passed = inputRef.val.length >= 6
              break
            case 'password_max':
              passed = inputRef.val.length <= 15
              break
            default:
              break
          }
          return passed
        })
        inputRef.error = !allPassed
        return allPassed
      }
      return true
    }
    onMounted(() => {
      emitter.emit('form-item-created', validateInput)
    })
    return {
      inputRef,
      validateInput,
      updateValue
    }
  },
})
</script>
